<?php

namespace Common\Model;

use Think\Model;

class File extends Model
{
    //文件上传
    public static function upload(){
        //实例化上传类
        $upload=new \Think\Upload();
        //设置附件上传大小
        $upload->maxSize=3145728;
        //设置附件上传类型
        $upload->exts=array('jpg','gif','png','jpeg');
        //设置附件上传目录
        $upload->rootPath='./Public/';
        $upload->savePath='./Uploads/';
        $upload->saveName=date('Ymd',time()).uniqid();
        $upload->autoSub=true;
        $upload->subName=date('Y',time()).'/'.date('m',time()).'/'.date('d',time());
        //上传文件,返回成功上传的文件信息数组
        $info=$upload->upload();
        if (!$info)
        {
            //上传错误提示错误信息
           //$message=self::error($upload->getError());
        }else{
            //上传成功
            //做图片压缩
            self::zoom($info['pic']['savename']);
            return $info['pic']['savename'];
        }
    }

    public static function sub($str)
    {
        return substr($str, 0,4).'/'.substr($str, 4,2).'/'.substr($str, 6,2).'/';
    }

    private function zoom($filename)
    {
        $image=new \Think\Image();
        $path='./Public/Uploads/'.self::sub($filename);
        $image->open($path.$filename);
        //按照原图的比例生成一个缩略图并保存
        $image->thumb(233,322)->save($path.'322_'.$filename);
        $image->thumb(150,150)->save($path.'150_'.$filename);
        $image->thumb(300,300)->save($path.'300_'.$filename);
        $image->thumb(98,125)->save($path.'125_'.$filename);
        $image->thumb(80,80)->save($path.'80_'.$filename);
    }

    public static function setUnlink($filename){
        $path='./Public/Uploads/';
        unlink($path.self::sub($filename).$filename);
        unlink($path.self::sub($filename).'150_'.$filename);
        unlink($path.self::sub($filename).'322_'.$filename);
        unlink($path.self::sub($filename).'300_'.$filename);
        unlink($path.self::sub($filename).'125_'.$filename);
        unlink($path.self::sub($filename).'80_'.$filename);
    }
}